package com.example.blogdesign.Service.Impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blogdesign.Entity.Blog;
import com.example.blogdesign.Entity.BlogComments;
import com.example.blogdesign.Entity.Follow;
import com.example.blogdesign.Entity.User;
import com.example.blogdesign.Mapper.BlogCommentsMapper;
import com.example.blogdesign.Mapper.BlogMapper;
import com.example.blogdesign.Service.IBlogService;
import com.example.blogdesign.Service.IFollowService;
import com.example.blogdesign.Service.IUserService;
import com.example.blogdesign.dto.Result;
import com.example.blogdesign.dto.UserDTO;
import com.example.blogdesign.utils.SystemConstants;
import com.example.blogdesign.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import static com.example.blogdesign.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.example.blogdesign.utils.RedisConstants.FEED_KEY;


@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IFollowService followService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;

    @Resource
    private BlogCommentsMapper blogCommentsMapper;

    //保存笔记
    @Override
    public Result<Long> saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess){
            return Result.fail("新增笔记失败");
        }
        //3. 查询笔记作者的所有粉丝（select * from tb_follow where follow_user_id = ?）
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId().toString()).list();
        //4.推送笔记id给粉丝
        for (Follow follow:follows) {
            Long userId = follow.getUserId();
            String key=FEED_KEY+userId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回
        return Result.ok(blog.getId());
    }

    //点赞和取消点赞
    @Override
    public Result<?> likeBlog(Long blogId) {
        String key=BLOG_LIKED_KEY+blogId;
        Long userId = UserHolder.getUser().getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //未点赞
        if (score==null) {
            //进行点赞
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", blogId).update();
            //点赞成功
            if (isSuccess) {
                //保存用户到 redis中的zset
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }else {
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", blogId).update();
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
        return Result.ok();
    }

    //查询热门博客
    @Override
    public Result<List<Blog>> queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page =query()
                .orderByDesc("liked")//根据点赞数排名
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(
                blog -> {
                    this.queryBlogUser(blog);
                    this.isBlogLiked(blog);
                });
        return Result.ok(records);
    }

    @Transactional
    @Override
    public Result<?> deleteBlogById(Long blogId) {
        Blog blog = getById(blogId);
        //删除图片
        String filename = blog.getImages();
        File file = new File(SystemConstants.IMAGE_UPLOAD_DIR, filename);
        FileUtil.del(file);
        //删除博客下面所有评论
        blogCommentsMapper.delete(new QueryWrapper<BlogComments>().eq("blog_id",blogId));
        //删除博客数据
        removeById(blogId);
        return Result.ok("博客删除成功");
    }

    @Override
    public Result<List<Blog>> queryMyBlog(Integer current) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        // 根据用户查询
        Page<Blog> page =query().eq("user_id", user.getId()).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    //查看当前用户是否点赞过该博客
    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user==null) {
            return;
        }
        String key=BLOG_LIKED_KEY+blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key,user.getId().toString());
        blog.setIsLike(score!=null);
    }


    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }


}
